<?php
/**
 * Description
 *
 * PHP version 7
 *
 * @category Custom
 * @package  Custom
 * @author   ryu <mo5467@126.com>
 * @date     2020-04-29 22:58:03
 * @lastTime 2020-05-02 00:19:58
 * @license  https://opensource.org/licenses/MIT MIT License
 * @link     none
 */
namespace Design\Other\ServiceLocator;

class ServiceLocator
{

    private $services = [];

    private $instantiated = [];


    public function addInstance(string $class, Service $service)
    {
        $this->instantiated[$class] = $service;

    }//end addInstance()


    public function addClass(string $class, array $params)
    {
        $this->services[$class] = $params;

    }//end addClass()


    public function has(string $interface) : bool
    {
        return isset($this->services[$interface]) || isset($this->instantiated[$interface]);

    }//end has()


    public function get(string $class) : Service
    {
        if (isset($this->instantiated[$class])) {
            return $this->instantiated[$class];
        }

        $args = $this->services[$class];

        switch (count($args)) {
        case 0:
            $object = new $class();
            break;
        case 2:
            $object = new $class($args[0], $args[1]);
            break;
        default:
            throw new \OutOfBoundsException('Too many argument given');
        }

        if (!$object instanceof Service) {
            throw new \InvalidArgumentException('Could not instance service');
        }

        $this->instantiated[$class] = $object;
        return $object;

    }//end get()


}//end class
